package com.yunpeng.dishes.biz.services.impl;

import com.yunpeng.dishes.biz.services.IListQueryService;
import com.yunpeng.dishes.common.constants.QueryConstants;
import com.yunpeng.dishes.common.enums.ResultCodeEnum;
import com.yunpeng.common.exception.BizException;
import com.yunpeng.common.paging.PagingQueryDO;
import com.yunpeng.common.paging.PagingQueryDTO;
import com.yunpeng.common.util.PagingQueryUtils;
import com.yunpeng.dishes.dao.mapper.IListMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * ListQueryServiceImpl
 * 列表服务
 *
 * @author hemw.it
 * @date 2019/9/25 15:43
 */
@Service
public class ListQueryServiceImpl implements IListQueryService {

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 通用查询方法
     *
     * @param queryDTO
     * @param queryList
     * @return
     * @throws BizException
     */
    private PagingQueryDTO commonQuery(PagingQueryDTO queryDTO, String queryList) throws BizException {
        if (queryDTO == null) {
            queryDTO = new PagingQueryDTO();
        }
        PagingQueryDO pagingQueryDO = new PagingQueryDO();
        pagingQueryDO.setCurrentPage(queryDTO.getCurrentPage());
        pagingQueryDO.setPageSize(queryDTO.getPageSize());
        pagingQueryDO.setOrderBy(PagingQueryUtils.getOrderBy(queryDTO));
        pagingQueryDO.setParameters(PagingQueryUtils.getParameters(queryDTO));

        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取映射方法
        String countMethod;
        String queryMethod;
        switch (queryList) {
            case QueryConstants.QUERY_FOR_FOOD_LIST_PAGE:
                countMethod = QueryConstants.QUERY_FOR_FOOD_LIST_PAGE;
                queryMethod = QueryConstants.COUNT_FOR_FOOD_LIST_PAGE;
                break;
            default:
                throw new BizException(ResultCodeEnum.NO_SUCH_METHOD_FAIL, "查询的列表未配置！");
        }

        //执行方法
        Integer count = sqlSession.selectOne(countMethod, pagingQueryDO);
        queryDTO.setDataCount(count);
        if (count > 0) {
            List<Map<String, Object>> queryResult = sqlSession.selectList(queryMethod, pagingQueryDO);
            queryDTO.setData(queryResult);
        }
        return queryDTO;
    }


    @Override
    /**
     * 用户列表页面数据
     *
     * @param queryDTO
     * @return
     * @throws BizException
     */
    public PagingQueryDTO query4FoodListPage(PagingQueryDTO queryDTO) throws BizException {
        PagingQueryDTO queryResult = commonQuery(queryDTO, QueryConstants.QUERY_FOR_FOOD_LIST_PAGE);
        //这里可以做一些私有的处理，例如计算列等
        return queryResult;
    }

}
